import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store=new Vuex.Store({
    state:{
        token: localStorage.getItem('token') || '',
        userInfo: null
    },
    mutations:{
        SET_TOKEN(state, token) {
            state.token = token
            localStorage.setItem('token', token)
        },
        SET_USER_INFO(state, userInfo) {
            state.userInfo = userInfo
        },
        LOGOUT(state) {
            state.token = ''
            state.userInfo = null
            localStorage.removeItem('token')
        }
    },
    actions: {
        login({ commit }, { token, userInfo }) {
            commit('SET_TOKEN', token)
            commit('SET_USER_INFO', userInfo)
        },
        logout({ commit }) {
            commit('LOGOUT')
        }
    },
    getters:{
        isAuthenticated: state => !!state.token,
        currentUser: state => state.userInfo
    }})

export default store